package top.itaso.app.ui.apps

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import top.itaso.lib.common.AppUtils


class AppsViewModel(application: Application) : AndroidViewModel(application) {
    private val mContext = getApplication<Application>().applicationContext

    /**
     * 示例集
     */
    private val _appData = MutableLiveData<List<AppEntity>>().apply {
        value = arrayListOf()
        getAppEntities()
    }

    /**
     * 示例集
     */
    private val _notifyLoading = MutableLiveData<Boolean>().apply {
        value = true
    }

    val mAppData: LiveData<List<AppEntity>> = _appData

    val mNotifyLoading: LiveData<Boolean> = _notifyLoading

    private fun getAppEntities() {
        GlobalScope.launch(Dispatchers.IO) {
            val appsInfo = AppUtils.getAppEntities(mContext)
            val newAppsInfo = arrayListOf<AppEntity>()
            for (appInfo in appsInfo) {
                val newAppInfo = AppEntity(
                    appIcon = appInfo.icon,
                    appName = appInfo.name,
                    appPackageName = appInfo.packageName,
                    appVersionName = appInfo.versionName,
                    appVersionCode = appInfo.versionCode,
                    isSystemApp = appInfo.isSystem,
                    appInstallPath = appInfo.installPath,
                    installTime = appInfo.installTime,
                    updateTime = appInfo.updateTime
                )
                newAppInfo.isEllipsize2Marquee = false
                newAppsInfo.add(newAppInfo)
            }
            _appData.postValue(newAppsInfo)
            _notifyLoading.postValue(false)
        }
    }
}